#include <dblib.h>
#include <params.h>
#include <dmeta.h>
#include <stdafx.h>
#include <constants.h>
#include <stdexcept>

#ifdef __cplusplus
extern "C" {
#endif

RETCODE __declspec(dllexport) xp_phon_dmeta(SRV_PROC *srvproc);

#ifdef __cplusplus
}
#endif

RETCODE __declspec(dllexport) xp_phon_dmeta(SRV_PROC *srvproc)
{
	std::string out1, out2;
	params *p1 = new params();
	params *p2 = new params();
	params *p3 = new params();
	RETCODE rc = XP_NOERROR;
	int numparams = params::getparamcount(srvproc);
	try
	{
		if (numparams != 3) {
			Dblib::printerror(srvproc, USAGE_DMETA);
			rc = XP_ERROR;
		}
		if (rc == XP_NOERROR) {
			params::getparam(srvproc, 1, p1);
			params::getparam(srvproc, 2, p2);
			params::getparam(srvproc, 3, p3);
			if (p1->isoutput || !p2->isoutput || !p3->isoutput) {
				Dblib::printerror(srvproc, USAGE_DMETA);
				rc = XP_ERROR;
			}
		}
		if (rc == XP_NOERROR) {
			std::string in = (char *)p1->cdata;
			MString dm(in);
			dm.DoubleMetaphone(out1, out2);
		}
	} catch (std::exception ex) {
		Dblib::printerror(srvproc, ERR_DMETA_EXCEPTION);
		rc = XP_ERROR;
	}
	if (rc == XP_NOERROR) {
		srv_paramsetoutput(srvproc, 2, (BYTE *)out1.c_str(), (int)out1.length(), FALSE);
		srv_paramsetoutput(srvproc, 3, (BYTE *)out2.c_str(), (int)out2.length(), FALSE);
	} else {
		srv_paramsetoutput(srvproc, 2, (BYTE *)"", 0, TRUE);
		srv_paramsetoutput(srvproc, 3, (BYTE *)"", 0, TRUE);
	}
	// Now return the number of rows processed
	srv_senddone(srvproc, SRV_DONE_MORE, (DBUSMALLINT)0, (DBINT)0);
	if (p1 != NULL)
		delete p1;
	p1 = NULL;
	if (p2 != NULL)
		delete p2;
	p2 = NULL;
	if (p3 != NULL)
		delete p3;
	p3 = NULL;
    return rc;
}

